package com.zhan.ielts.tools;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.zhan.frame.core.utils.FileUtils;

/**
 * Created by Admin on 2016/3/23.
 */
public class YouDaoPull {
    //    解析文件
    public static void parse(String path) {
        File file = new File(path);
        BufferedReader reader = null;
        String className = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://192.168.1.188:3306/ieltsdb?zeroDateTimeBehavior=convertToNull";
        String username = "ieltsdba";
        String userpass = "zaq1_XSW2";
        Connection con = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            String[] fileList = null;//{"nul-1449661114610"};
            if(!file.exists() || !file.isDirectory()) {
                System.out.println("文件读取错误");
                return;
            }
            fileList = file.list();
            Class.forName(className);
            con = DriverManager.getConnection(url, username, userpass);
            con.setAutoCommit(false);
            stmt = con.prepareStatement("replace into t_dictionary_temp1(word,content) VALUES (?, ? );");
            for (int i = 0; i < fileList.length; i++) {
                String fileName = fileList[i];
                JSONObject json = null;
                try {
                    json = YouDaoFile.parserHtml(path + fileName);
                }catch (Exception e){
                    System.out.println(fileName);
                    continue;
                }
                if(json.get("state").equals("error")){
                    System.out.println(fileName + ":" + json.get("message"));
                    continue;
                }
                String name = fileName;
                stmt.setString(1,name);
                JSONObject content = null;
                if(json.containsKey("content")){
                    content = (JSONObject) json.get("content");
                    System.out.println(content.toString());
                    stmt.setString(2, YouDaoFile.filterOffUtf8Mb4(content.toString()));
                }else {
                    stmt.setString(2,"");
                }
                stmt.addBatch();
                if(i%100==0){
                    stmt.executeBatch();
                    con.commit();
                    con.setAutoCommit(false);
                }
            }
            stmt.executeBatch();
            con.commit();
            con.close();
        } catch (java.lang.ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    public static void getHTML(String path,String textPath){
        String word =  FileUtils.readFile(textPath);
        List<String> list = Arrays.asList(word.split(","));
        for (int i = 0; i < list.size(); i++) {
            Map<String,String> param = new HashMap<String,String>(3);
            param.put("le","eng");
            param.put("q",list.get(i));
            param.put("keyfrom","dict.top");
            String result = HttpUtils.get("http://dict.youdao.com/search",param);
            FileUtils.createFile(path+list.get(i),result);
        }
    }
    public static void getAudio(String path,String audioPath){
        File word =  new File(path);
        String url = "http://dict.youdao.com/dictvoice";
        List<String> list = Arrays.asList(word.list());
        for (int i = 0; i < list.size(); i++) {
            boolean flag = true;
            JSONObject html = YouDaoFile.parserAudio(word.getAbsolutePath()+"\\"+list.get(i));
            if (html.get("state") != "ok"){
                System.out.println(list.get(i));
                continue;
            }
            if (!html.getJSONObject("content").containsKey("radio")){
                System.out.println(list.get(i));
                continue;
            }
            JSONArray json = html.getJSONObject("content").getJSONArray("radio");
            /*for (int j = 0; j < json.size(); j++) {
                JSONObject urls = json.getJSONObject(j);
                String wordUrl = urls.getString("url");
                String type = "";
                if (wordUrl.indexOf("type=")>-1){
                    type = wordUrl.substring(wordUrl.indexOf("type=")+5,wordUrl.length());
                }
                if(type.equals("1")){
                    continue;
                }
                flag = false;
                Map<String,String> param = new HashMap<String,String>(3);
                param.put("audio",list.get(i));
                param.put("type",type);
                if (!"".equals(type)){
                    type = "_"+type;
                }
                //HttpUtils.downLoad(url,param,audioPath+list.get(i)+type+".mpeg");
            }*/
            String bestType = "x";
            for (int j = 0; j < json.size(); j++) {
                JSONObject urls = json.getJSONObject(j);
                String wordUrl = urls.getString("url");
                String type = "";
                if (wordUrl.indexOf("type=")>-1){
                    type = wordUrl.substring(wordUrl.indexOf("type=")+5,wordUrl.length());
                }
                if(type.equals("1")){
                    bestType = type;
                    flag = false;
                    break;
                }
                if(type.equals("") && !bestType.equals("1")){
                    bestType = type;
                    flag = false;
                    continue;
                }
                if((type.equals("2") || type.equals("3")) && !bestType.equals("") && !bestType.equals("1")){
                    bestType = type;
                    flag = false;
                    continue;
                }

            }
            if(flag){
                System.out.println(list.get(i));
            }else{
                Map<String,String> param = new HashMap<String,String>(3);
                param.put("audio",list.get(i));
                param.put("type",bestType);
                if (!"".equals(bestType)){
                    bestType = "_"+bestType;
                }
                File file = new File(audioPath+list.get(i)+bestType+".mpeg");
                if (!file.exists()){
                    HttpUtils.downLoad(url,param,audioPath+list.get(i)+bestType+".mpeg");
                }
            }
        }
    }
    public static void getText(String filePath){
        File file = new File(filePath);
        FileOutputStream fos = null;
        BufferedReader reader = null;
        String className = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://192.168.1.188:3306/ieltsdb?zeroDateTimeBehavior=convertToNull";
        String username = "ieltsdba";
        String userpass = "zaq1_XSW2";
        Connection con = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        StringBuilder words = new StringBuilder();
        try {
            Class.forName(className);
            con = DriverManager.getConnection(url, username, userpass);
            con.setAutoCommit(false);
            stmt = con.prepareStatement("select word from t_word_ielts;");
            rs = stmt.executeQuery();
            while (rs.next()){
                String word = rs.getString(1);
                words.append(word);
                words.append(",");
            }
            con.close();
            String result = words.toString();
            if(result.endsWith(",")){
                result = result.substring(0,result.length()-1);
            }
            fos = new FileOutputStream(file);
            fos.write(result.getBytes("utf-8"));
            fos.close();
        } catch (java.lang.ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        String path = "D:\\youdao\\lost-20160315\\";
        String textPath = "D:\\youdao\\lost-20160315.txt";
//        getText(textPath);
        String audioPath = "D:\\youdao\\lostAudio-20160304\\";
//        getHTML(path,textPath);
//        getAudio(path,audioPath);
        parse(path);
    }
}
